package org.jks.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.config.Config;
import org.jks.constant.Constants;
import org.jks.model.User;
import org.jks.util.JsonUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class PageController {
	@RequestMapping("/")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<String,Object> model) {
		Config.init(request, response, session, model);
		User u = isLogin(session);
		if(u != null)
		{
			model.put("user", JsonUtil.Object2Json(u));
			return new ModelAndView("index", model);
		}
		else
		{
			return new ModelAndView("login", model);
		}
	}
	
	@RequestMapping("/index")
	public ModelAndView index1(HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<String,Object> model) {
		Config.init(request, response, session, model);
		User u = isLogin(session);
		if(u != null)
		{
			model.put("user", JsonUtil.Object2Json(u));
			return new ModelAndView("index", model);
		}
		else
		{
			return new ModelAndView("login", model);
		}
	}
	
	@RequestMapping("/login")
	public ModelAndView login(HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<String,Object> model) {
		Config.init(request, response, session, model);
		return new ModelAndView("login", model);
	}
	
	
	@RequestMapping("/logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<String,Object> model) {
		session.removeAttribute(Constants.SESSION_ACCOUNT);
		Config.init(request, response, session, model);
		return new ModelAndView("login", model);
	}
	
	@RequestMapping("/error")
	public ModelAndView error(HttpServletRequest request, HttpServletResponse response, HttpSession session, Map<String,Object> model) {
		Config.init(request, response, session, model);
		return new ModelAndView("error", model);
	}
	
	private User isLogin(HttpSession session)
	{
		return (User)session.getAttribute(Constants.SESSION_ACCOUNT);
	}
}
